import React, {useCallback, useEffect, useState} from 'react';
import { useDispatch } from 'react-redux';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import _ from 'underscore';

import PrivateRoute from '@/hooks/PrivateRoute';
import Loading from '@/components/Loading';
import { baseRouters, addDynamicRoute } from "@/router";
import { flatRoutes } from '@/utils/routeUtils';
import LayoutLoader from '@/layout';
import { NOTFOUND } from '@/config/url';
import { getGrid } from '@/utils';
import { validate } from '@/service';
import { setStore } from '@/reducers/main';

function Application(props) {
    const initState = () => ({
        loading: true,
        routerTree: baseRouters,
        routers: flatRoutes(baseRouters),
    }),
    [state, setState] = useState(initState),
    dispatch = useDispatch();

    /**
     * 检查用户是否登录（也可以获取用户信息）
     *
     */
    const checkLogged = () => {
        validate().then(response => {
            let routes = state.routers || [],
                {expire, user, token} = response?.data || {},
                authSource = [], // 后端返回的数据
                authRoutes = addDynamicRoute(authSource), // 这里需要传入后端返回的数据
                appRoutes = flatRoutes(routes.concat(authRoutes)), // 应用的所有路由
                routerTree = baseRouters.concat(authSource); // 原始路由数据

            window.SITE_CONFIG['appRouterTree'] = routerTree;
            window.SITE_CONFIG['appRouteArray'] = appRoutes;

            setState(o => ({
                ...o,
                loading: false,
                routers: appRoutes,
                routerTree,
            }));

            // 记录用户信息
            dispatch(setStore({userInfo: user}));
            // 请求用户基础数据
            if(RESPONSE_SUCCESS_CODE === response?.code) {
                // 更新redux中个人信息
            }
        }).catch(e => {
            // 设置全局变量，后续可能会使用
            window.SITE_CONFIG['appRouteArray'] = flatRoutes(state.routers);
            setState(o => ({
                ...o,
                loading: false,
            }));
        });
    };

    /**
     * 监听页面宽度变化
     *
     */
    const resizeListen = useCallback(() => {
        let grid = getGrid();

        // dispatch(setStore({
        //     grid,
        //     isMobile: isMobileApp(grid),
        //     isPad: isPadApp(grid),
        //     isPc: isPcApp(grid),
        // }));
    }, []);

    // 这是入口文件，页面间切换不会触发，只有应用首次加载时才会触发
    useEffect(() => {
        // 判断是否登录
        checkLogged();
        // 先执行一次屏幕宽度计算
        resizeListen();

        // 监听页面宽度变化，节流
        const handleResize = _.throttle(resizeListen, 200);
        window.addEventListener('resize', handleResize, false);

        return () => {
            window.removeEventListener('resize', handleResize, false);
        }
    }, []);

    return (
        <>
            {
                state.loading ?
                    <Loading tip="正在拼命赶来..."/>
                    :
                    <Router>
                        <LayoutLoader routerTree={state.routerTree || []}>
                            <Switch>
                                {
                                    (state.routers || []).map(item => {
                                        return <PrivateRoute
                                            key={item.url}
                                            exact
                                            path={item.url}
                                            className={`${window.SITE_CONFIG['ROUTE_CLASS_NAME']} ${(item.url||'').replace(/\//g, '').replace(/-/g, '')}`}
                                            component={item.component}
                                        />
                                    })
                                }
                                <Route
                                    render={(props) => {
                                        let Comp = baseRouters.find(i => i.url === NOTFOUND)?.component || null;

                                        return <Comp {...props} />
                                    }}
                                />
                            </Switch>
                        </LayoutLoader>
                    </Router>
            }
        </>
    );
}

export default Application;


